var ws, spage, uid, photo='';
var upload_pic = [];
var pic_index = 1;
var tid, aid;
document.addEventListener('plusready', function(){ 
	ws = plus.webview.currentWebview();
	tid = ws.tid;	//中医2；西医109
	spage = ws.spage;	//药品详情页
	aid = ws.aid;	//药品id
	pid = ws.pid;	//药品列表页
	uid = plus.storage.getItem('uid');
	if(aid){
		$('.mui-title').text('编辑药品');
		$('button').text('修改');
	}else{
		$('.mui-title').text('添加药品');
		$('button').text('添加');
	}
//	console.log(apiRoot+"/home/medicinal/MedinicalInfo/aid/"+aid+"/type/"+tid);
	$.ajax({
		type:"get",
		url:apiRoot+"/home/Classify/Classify",
		dataType :'json',
		success :function(data){
//			console.log(JSON.stringify(data));
			if(data.length > 0){
				var list = '';
				$.each(data, function(k, v) {
					list += '<option value="'+v.classname+'">'+v.classname+'</option>';
				});
				$('select[name=type]').html(list); 
			}
		},
		error :function(e){
			console.log(JSON.stringify(e));
			errortoast();
		}
	});
	if(aid && $('select[name=type]').html() != ''){
		showWating();		
		$.ajax({
			type:"get",
			url:apiRoot+"/home/medicinal/MedinicalInfo",
			data :{
				aid :aid,
				type :tid
			},
			complete :function(){
				plus.nativeUI.closeWaiting();
			},
			dataType :'json',
			success :function(data){
				if(data){
					$.each(data, function(k, v){
						$('.Medicine *[name]').each(function(){
							var str = $(this).attr('name');
							if(str == k){ 
								$(this).val(v);
							}
						})
					})
					$.each(data.pro, function(k, v) {
						$('#photo').before('<img src="'+webRoot+v+'"/>');
					});
					$('.rz-img img[id!=photo]').on('longtap', longdel);
					$('#content').html(data.body.replace(/src="/g ,'src="'+webRoot));
				}
			},
			error :function(e){
				console.log(JSON.stringify(e));
				errortoast();
			}
		});
	}
	$('.uploadpic').on('tap', function(){
		mui('#sheet1').popover('toggle');
	})
	//选择拍照添加
	$('.paizhao').on('tap', function(){
		type = 'text';
		var cmr = plus.camera.getCamera(); 
		cmr.captureImage( function(path){
			appendPic1(path);
		}, function(err){}, {index:1} );   
	})
	//选择相册添加
	$('.photo').on('tap', function(){
		type = 'text';
		plus.gallery.pick( function(path){
		 	appendPic1(path);
		}, function(error){}, {} );
	})
    var index = 1;
	var files = [];
	// 添加照片
	function appendPic1(p) {
		//创建新路径 
//		var newPath = p.replace(/\./g , new Date().getTime()+'.');
//		plus.zip.compressImage({
//				src:p,
//				dst:newPath,
//				quality:20
//			},
//			function() {//成功回调
				files.push({name:"uploadkey"+index,path:p});
				index++;
				upload(files);
//			},function(error) {
//				toast('压缩图片失败');
//		});
	}
	//点击添加
	$('.res_pasw').on('tap', function(){
		var type = $('select[name=type]').val();//所属分类
		if(aid){
			photo = '';
			$('.rz-img img[id!=photo]').each(function(){
				var _this = $(this);
				var p = _this.attr('src');
				p = p.replace(webRoot, '')
				photo += '|-|' + p + '|,|';
			})
		}
		if(!photo || photo == ''){
			toast('请上传3张展示图片');return;
		}
		photo = photo.substr(3);	//从第四个字符开始
		var isNull = false;
		$("input[id!='body'][type !='file'][type !='hidden'], textarea").each(function() {
			var _this = $(this);
			var _val = _this.val(); 
			if(!_val.trim()) {
				toast('请填写' + _this.siblings().eq(0).text());
				setTimeout(function () {
					_this.focus();
				},50);
				isNull = true;
				return false;
			}
		});
		if(isNull) {
			return;
		}
		type = $('select').val();//所属分类
		var body = $('#content').html();
		if(body == '<p>请输入图文详情</p>'){
			toast('请输入图文详情');return;
		}
            body = body.replace(webRoot, "");
		var str = $('form[name=minfo]').serialize();
		var data = str+"&uid="+uid+"&tid="+tid+"&type="+type+"&photo="+photo+"&body="+body;
		if(aid){
			data += "&aid="+aid;
		}
		showWating();
		$.ajax({
			type:"post",
			url:apiRoot+"?m=home&c=medicinal&a=addMedicine",
			data :data,
			success :function(data){
				plus.nativeUI.closeWaiting()
				toast('操作成功');
				var cur = plus.webview.getWebviewById(pid);
				cur.evalJS('Me_drug()');
				plus.webview.getWebviewById(spage).close();
				ws.close();
			},
			error :function(e){
				console.log(JSON.stringify(e));
			}
		});
	})
	//点击上传展示图
	$('#photo').on('tap', function(){
		if($('.rz-img img[id!=photo]').length >= 3){
			toast('展示图已有3张');return;
		}
		type = 'pic';
		plus.gallery.pick( function(path){
			upload_pic.push({name:"uploadkey",path:path});
			upload(upload_pic);
		}, function(error){}, {} );
	})
	//上传图文详情
	$('.uploadpic').on('tap', function(){
		$('#imageUpload').click();
	})
}, false)
var type = '';
//将图片上传到服务器
function upload(arr){
	var wt = plus.nativeUI.showWaiting('处理中');
	var  task = plus.uploader.createUpload(apiRoot+'?m=Home&c=Member&a=uploadOne',{ method:"POST"},
	function ( t, status ) {  
		if ( status == 200 ) {
			var pro = t.responseText;
			console.log(pro);
			if(pro == -1){
				toast('图片上传失败');
			}else{
				if(type == 'pic'){	//展示图
					$('.rz-img').prepend('<img src="'+webRoot+pro+'"/>');
					photo += '|-|'+pro+'|,|';
				}else{	//图文详情
					$('#content').append('<img src="'+webRoot+pro+'" style="width: 100%;"/>');
				}
			}
			wt.close(); 
		} else {
			plus.nativeUI.toast( "上传失败："+status );
			wt.close();
		}  
	});
	for(var i = 0; i < arr.length; i++){
		var f = arr[i];
		task.addFile(f.path,{key:f.name});
	}
	task.start();
}
//长按删除图片
function longdel(){
	var _this = $(this);
	plus.nativeUI.confirm('确认删除该图片', function(e){
		if(e.index == 1){
			console.log('删除')
			_this.remove();
		}
	}, null, ['取消', '确认'])
}